<?php

namespace app\admin\common\controller;

use app\admin\framework\api\Permission;
use app\common\model\Order;
use app\common\model\OrderBoardItem;
use app\common\model\OrderTrip;
use app\common\service\OrderService;
use app\common\service\UserService;
use app\common\utils\Excel;
use think\facade\Db;

#[Permission('车辆订单', 'Order', 9)]
class OrderlistController
{
    private $deptId = 0;
    
    public function __construct()
    {
        $this->deptId = UserService::getValue('dept_id');
    }
    
    
    #[Permission('参数')]
    public function option()
    {
        return apiSuccess(data: [
            'status' => Order::STATUS
        ]);
    }
    
    #[Permission('查询')]
    public function select()
    {
        $keyword = request()->get('keyword', '');
        $orderStatus = request()->get('orderStatus');
        $start_dept_id = request()->get('start_dept_id');
        $end_dept_id = request()->get('end_dept_id');
        $field = '*';

        $where[] = ['order_sn|accept_mobile|shipper_mobile|shipper_name|accept_name|address|end_address|car_shelf_num','like','%'.$keyword.'%'];

        $whereOr = [];

        $userInfo = UserService::get();
        $roles = UserService::getRoleIds($userInfo['id']);
        if(!in_array(1,$roles)){
            if ($userInfo['dept_id'] != 91) {
                $where[] = ['dept_id', '=', $userInfo['dept_id']];
            }
        }

        // 数据权限
        $dataAuth = UserService::getRoleDataAuth($userInfo['id']);
        if (!empty($dataAuth)) {
            $where[] = ['dept_id', 'in', $dataAuth];
        }

        $timeBetween = request()->get('timeBetween',[]);
        if(!empty($timeBetween)){
            $where[] = ['create_time','between',$timeBetween];
        }
        if(isset($orderStatus) && $orderStatus >= 0){
            $where[] = ['status', '=', $orderStatus];
        }
        if(isset($start_dept_id) && !empty($start_dept_id)){
            $where[] = ['dept_id', '=', $start_dept_id];
        }
        if(isset($end_dept_id) && !empty($end_dept_id)){
            $where[] = ['end_dept_id', '=', $end_dept_id];
        }
        $list = Order::where($where)
            ->field($field)
            ->with(['dept','endDept','insure'])
            ->order('id desc')
            ->paginate()
            ->each(function($item){
                if (isset($item->status)) {
                    $item->order_status_text = Order::STATUS[$item->status];
                } else {
                    $item->order_status_text = '';
                }
                if (isset($item->contract) && !empty($item->contract)) {
                    if (strpos($item->contract, 'http://sc.dm.ccjwcm.com') !== false) {
                        $item->contract = str_replace('http://sc.dm.ccjwcm.com', 'http://admin.nmshicheng.com', $item->contract);
                    }
                }
            });
        return apiSuccess(data: ['list' => $list->items(), 'total' => $list->total()]);
    }
    
    #[Permission('物流追踪')]
    public function logistics()
    {
        $id = request()->get('id', 0);
        return apiSuccess(data: OrderService::getLogistics($id));
    }
    
    #[Permission('编辑')]
    public function update()
    {
        $id = request()->post('id', 0);
        $status = request()->post('status', 0);
        $data = request()->post('data');
        OrderService::update($id, $status, $data, 'end');
        return apiSuccess('编辑成功');
    }
    
    #[Permission('excel')]
    public function excel()
    { 
        $keyword = request()->get('keyword', ''); 
        $list = OrderService::getLists('dept.list', [ 
            'keyword' => $keyword,
            'identity' => 'end'
        ],true);
        
        $arr = [];
        foreach ($list as $key => $value){ 
            $boardItem = Db::name('order_board_item')->where('order_id',$value->id)->find(); 
            if(!empty($boardItem)){
                $arr[] = [
                    $value->create_time,
                    $value->address,
                    $value->end_address,
                    $value->car_brand,1,
                    $value->pay_type_text,
                    $value->shipper_name,
                    $value->shipper_mobile,
                    $boardItem['landing_price'],
                    $boardItem['transfer_price'],
                    $boardItem['freight_price'],
                    $value->car_shelf_num,
                ];
            } 
        } 
        
        $filePath = Excel::import('', [
            '日期', '起运地', '到达地', '车辆名称', '台数', '到付', '收车人', '电话', '接车费', '中转费', '付司机运费', '车架号'
        ], $arr); 
        return apiSuccess(data: ['url'=>getImageUrl($filePath)]);
    }

    #[Permission('操作订单')]
    public function operateOrder()
    {
        $order_id = request()->get('order_id');
        $field = '*';
        $where[] = ['order_id', '=', $order_id];

        $list = OrderTrip::where($where)
            ->field($field)
            ->with(['startDept','nowDept','endDept'])
            ->order('id desc')
            ->select()
            ->each(function($item){
                if (isset($item->status)) {
                    $item->order_status_text = Order::ORDER_TRIP_STATUS[$item->status];
                } else {
                    $item->order_status_text = '';
                }
            });
        return apiSuccess(data: ['list' => $list, 'total' => count($list)]);
    }

    #[Permission('发车订单')]
    public function departOrder()
    {
        $order_id = request()->get('order_id');
        $field = '*';
        $where[] = ['order_id', '=', $order_id];

        $list = OrderBoardItem::where($where)
            ->field($field)
            ->with(['board','startDept','dept','endDept','nextDept'])
            ->order('id desc')
            ->select();
        return apiSuccess(data: ['list' => $list, 'total' => count($list)]);
    }

    #[Permission('订单作废')]
    public function cancelFun()
    {
        $order_id = request()->post('order_id');
        $remarks = request()->post('remarks');
        if (!$order_id) {
            return apiError('参数错误');
        }
        $order = Order::where('id', $order_id)->find();
        if ($order && $order->status != 8) {
            $order->status = 8;
            $order->cancel_time = date("Y-m-d H:i:s");
            $order->remarks = $remarks;
            if ($order->save()) {
                return apiSuccess('操作成功');
            } else {
                return apiError('操作失败');
            }
        }
        return apiError('订单错误');
    }
}